package com.huike.business.service.impl;


import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.domain.TbClue;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.common.core.domain.entity.SysDictData;
import com.huike.common.core.domain.entity.SysUser;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 商机跟进记录Service业务层处理
 *
 * @author wgl
 * @date 2021-04-28
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {


    @Autowired
    private TbBusinessTrackRecordMapper trackRecordMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public void addBusinessTrackRecord(BusinessTrackVo businessTrackVo, SysUser user) {

        // 添加 商机 追踪记录
        TbBusinessTrackRecord record = new TbBusinessTrackRecord();

        record.setCreateBy(user.getUserName());

        //数据填充 数据copy
        BeanUtils.copyProperties(businessTrackVo, record);

        // TODO 填充数据不完善
        record.setCreateTime(new Date());
        //执行业务
        trackRecordMapper.insertTrackRecord(record);

        // 修改 商机 状态等信息
        TbBusiness tbBusiness = new TbBusiness();

        // 设置 商机id
        tbBusiness.setId(record.getBusinessId());

        // 设置跟进时间
        tbBusiness.setCreateTime(new Date());

        // 设置 商机的跟踪状态 为 跟进状态
        tbBusiness.setStatus(TbClue.StatusType.FOLLOWING.getValue());

        //数据填充 数据copy
        //TODO 填充数据不完善
        businessMapper.updateTbBusiness(tbBusiness);
    }

    /**
     * 查询商机跟进表
     * @param id 商机id
     */
    @Override
    public List<TbBusinessTrackRecord> list(Long id) {
        // 商机 跟进基础信息
        List<TbBusinessTrackRecord> list = trackRecordMapper.list(id);

        for (TbBusinessTrackRecord record : list) {
            String keyItems = record.getKeyItems();

            // 判断 商机是否 有 keyItems
            if (keyItems==null){
                break;
            }

            String[] item = keyItems.split(",");
            ArrayList<String> items = new ArrayList<>();
            // 遍历查询 字典 中对应的 沟通重点信息 封装为集合
            for (String s : item) {
                items.add(sysDictDataMapper.selectDictLabel("communication_point", s));
            }
            // 设置keys
            record.setKeys(items);
        }
        // 返回
        return list;
    }
}
